/*
 * image_cache.cpp
 *
 *  Created on: 2024年7月17日
 *      Author: ZKSWE Develop Team
 */

#include "common.h"
#include "image_cache.h"
#include "utils/BitmapHelper.h"

namespace misc {

#define CACHE_SIZE    32  // 缓存区大小，表示缓存多少张图片

typedef struct {
	char path[128];
	struct _bitmap_t *bmp;
	int weight;
} SCacheInfo;

static SCacheInfo _s_cache_info_list[CACHE_SIZE];

void image_cache(const char *path) {
	bool isExist = false;
	int index = -1;

	char filePath[128];
	if (FILE_EXIST(path)) {
		strcpy(filePath, path);
	} else {
		strcpy(filePath, RESOURCE(path).c_str());
	}

	for (int i = 0; i < CACHE_SIZE; ++i) {
		if (strcmp(_s_cache_info_list[i].path, filePath) == 0) {
			_s_cache_info_list[i].weight++;
			isExist = true;
		} else if (_s_cache_info_list[i].bmp) {
			_s_cache_info_list[i].weight--;
			if ((index == -1) ||
				(_s_cache_info_list[index].bmp && (_s_cache_info_list[index].weight > _s_cache_info_list[i].weight))) {
				index = i;
			}
		} else if ((index == -1) || _s_cache_info_list[index].bmp) {
			index = i;
		}
	}

	if (!isExist) {
		if (_s_cache_info_list[index].bmp) {
			BitmapHelper::unloadBitmap(_s_cache_info_list[index].bmp);
		}
		BitmapHelper::loadBitmapFromFile(_s_cache_info_list[index].bmp, filePath);
		strcpy(_s_cache_info_list[index].path, filePath);
		_s_cache_info_list[index].weight = 1;
	}
}

void image_cache_release() {
	for (int i = 0; i < CACHE_SIZE; ++i) {
		if (_s_cache_info_list[i].bmp) {
			BitmapHelper::unloadBitmap(_s_cache_info_list[i].bmp);
		}
	}

	memset(_s_cache_info_list, 0, sizeof(_s_cache_info_list));
}

}
